package com.cheer.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.dao.OaChangeHistoryDao;
import com.cheer.dto.OaChangeHistoryPageDTO;
import com.cheer.entity.OaChangeHistoryEntity;
import com.cheer.entity.OaLearnClassEntity;
import com.cheer.service.OaChangeHistoryService;
import com.cheer.service.OaLearnClassService;
import com.cheer.vo.OaChangeHistoryListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("oaChangeHistoryService")
public class OaChangeHistoryServiceImpl extends ServiceImpl<OaChangeHistoryDao, OaChangeHistoryEntity> implements OaChangeHistoryService {

    @Autowired
    private OaChangeHistoryDao oaChangeHistoryDao;

    @Autowired
    private OaLearnClassService oaLearnClassService;

    @Override
    public IPage<OaChangeHistoryListVO> page(OaChangeHistoryPageDTO oaChangeHistoryPageParam) {

        IPage<OaChangeHistoryListVO> page = new Page<>(oaChangeHistoryPageParam.getPageNum(), oaChangeHistoryPageParam.getPageSize());
        page = oaChangeHistoryDao.selectPage(page, oaChangeHistoryPageParam);

        Set<String> departmentIds = new HashSet<>();
        page.getRecords().forEach( oaChangeHistoryListVO ->{
            departmentIds.add(oaChangeHistoryListVO.getSourceDepartment());
            departmentIds.add(oaChangeHistoryListVO.getTargetDepartment());
        });
        if(CollectionUtil.isNotEmpty(departmentIds)){
            List<OaLearnClassEntity> oaLearnClassEntities = (List<OaLearnClassEntity>) oaLearnClassService.listByIds(departmentIds);
            Map<Integer, List<OaLearnClassEntity>> map = oaLearnClassEntities.stream().collect(Collectors.groupingBy(OaLearnClassEntity::getId));
            page.getRecords().forEach(oaChangeHistoryListVO -> {

                String sourceDepartmentId = oaChangeHistoryListVO.getSourceDepartment();
                String targetDepartmentId = oaChangeHistoryListVO.getTargetDepartment();

                OaLearnClassEntity sourceDepartment = map.get(Integer.valueOf(sourceDepartmentId)).get(0);
                oaChangeHistoryListVO.setSourceDepartment(sourceDepartment.getName());

                OaLearnClassEntity targetDepartment = map.get(Integer.valueOf(targetDepartmentId)).get(0);
                oaChangeHistoryListVO.setTargetDepartment(targetDepartment.getName());

            });
        }

        return page;
    }
}